package mainpackage;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JComponent;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class CreepingLine extends JComponent {
    private Font font;
    private String text;
    private Point2D textPos;
    private double textWidth;
    private double textOffset;
    private Timer timer;
    private int delta;

    FontMetrics fontMetrics;
    FontRenderContext renderContext;
    GlyphVector glyphVector;
    Rectangle2D visualBounds;

    public CreepingLine(String text) {
        this.text = text;
        //delta = 1;
        timer = new Timer(25, new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                textOffset -= delta;
                double maxOffset = 0.5 * (textWidth + getWidth());
                if (textOffset < -maxOffset){
                    textOffset = maxOffset;
                }
                repaint();
            }
        });
    }

    public CreepingLine() {
        this("");
    }

    public void setText(String text) {
        this.text = text;
        textPos = null;
    }

    public void setFont(Font font) {
        this.font = font;
        textPos = null;
    }

    public void setSpeed(int deltaPixels, int delayMilliseconds) {
        delta = deltaPixels;
        timer.setDelay(delayMilliseconds);
    }

    public void start() {
        timer.start();
    }

    public void stop() {
        timer.stop();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g.setFont(font);
        g.setColor(Color.red);
        if (textPos == null)
            computeTextPosition(g2d);
        double x = 0.5 * getWidth() + textPos.getX() + textOffset;
        double y = 0.5 * getHeight() + textPos.getY();
        g.drawString(text, (int) x, (int) y);
    }

    private void computeTextPosition(Graphics2D g2d){
        fontMetrics = g2d.getFontMetrics();
        renderContext = g2d.getFontRenderContext();
        glyphVector = font.createGlyphVector(renderContext, text);
        visualBounds = glyphVector.getVisualBounds();
        textWidth = fontMetrics.getStringBounds(text, g2d).getWidth();
        double x = -0.5 * textWidth;
        double y = -0.5 * visualBounds.getHeight() - visualBounds.getY();
        textPos = new Point2D.Double(x, y);
        textOffset = 0.5 * (textWidth + getWidth());
    }
}
